<template>
  <!--角色管理 -->
  <div class="page-padding-bg">

    <div class="user">
      <div class="user_title">
        <div> <span>角色名：</span><lay-input v-model="rolename" size="sm" placeholder="请输入" @keydown.enter="search_table"></lay-input></div>
        <!-- <div> <span>角色代码：</span><lay-input size="sm" v-model="rolecode" placeholder="请输入" @keydown.enter="search_table"></lay-input></div> -->
        <div>
          <lay-button class="btn-search" size="sm" type="normal" @click="search_table"> 查询</lay-button>
          <lay-button class="btn-resert" size="sm" @click="resert">重置</lay-button>
        </div>
      </div>
      <div class="user_btn">
        <lay-button class="btn-add" size="sm" type="primary" @click="add" v-permissions="'role_add'"> 新增</lay-button>
        <!-- <lay-button size="sm" type="primary"> 修改</lay-button>
      <lay-button size="sm" type="danger"> 删除</lay-button> -->
        <!-- <lay-button size="sm" type="" @click="authority_open"> 分配权限</lay-button> -->
      </div>
      <div class="user_table">
        <lay-table :resize="true" :height="'100%'" :columns="columns" :data-source="dataSource">
          <template v-slot:operator="{ row }">
            <lay-button class="btn-edit" size="xs" type="primary" @click="edit_tab(row)" v-permissions="'role_edit'" > 修改</lay-button>
            <lay-button class="btn-delete" size="xs" type="danger" @click="del_tab(row)" v-permissions="'role_delete'"> 删除</lay-button>
       
            <lay-button class="btn-auth" size="xs" type="" @click="authority_open(row)" v-permissions="'role_perss'"> 分配权限</lay-button>
            <lay-button class="btn-view" size="xs" type="" @click="view_tab(row)" v-permissions="'role_view'">查看</lay-button>
          </template>
          <template #state="{ row }">
            <lay-switch v-model="row.state" onswitch-text="开启" unswitch-text="关闭" onswitch-value="0" unswitch-value="1" @change="switch_change(row,$event)"></lay-switch>
          </template>
        </lay-table>
        <Pagination :currentPage="currentPage" :limit="limit" :total="total" @page_change="page_change"></Pagination>
      </div>

      <!-- 弹层 -->
      <lay-layer v-model="is_visible" :area="['800px', '500px']" :title="visibleTitle" :btn="visible_opteron" :shadeClose="false" >
        <div style="padding: 20px 40px 20px 20px;">
          <lay-form :model="form" ref="layFormRef11">
            <lay-form-item label="角色名" prop="rolename" required>
              <lay-input v-model="form.rolename" size="sm" :disabled="isAddEdit=='view'"></lay-input>
            </lay-form-item>
            <lay-form-item label="角色代码" prop="rolecode" required>
              <lay-input v-model="form.rolecode" size="sm" :disabled="isAddEdit=='view'"></lay-input>
            </lay-form-item>

            <lay-form-item label="用户" prop="userList" required>
              <lay-select v-model="form.userList" multiple allow-clear placeholder="请选择" style="width: 100%;" size="sm" :disabled="isAddEdit=='view'">
                <lay-select-option :value="item.key" :label="item.title" v-for="item in userList" :key="item.key"></lay-select-option>
              </lay-select>
            </lay-form-item>
            <lay-form-item label="状态" prop="state" required>
              <!-- <lay-input v-model="form.state" size="sm"></lay-input> -->
              <lay-switch v-model="form.state" onswitch-text="开启" unswitch-text="关闭" :disabled="isAddEdit=='view'||!cannotEdit"></lay-switch>
            </lay-form-item>
            <lay-form-item label="描述" prop="describes" :required="false">
              <lay-textarea placeholder="请输入描述" v-model="form.describes" rows="3" show-count :disabled="isAddEdit=='view'">
              </lay-textarea>
            </lay-form-item>

          </lay-form>
        </div>
      </lay-layer>

      <!-- 权限弹层 -->
      <lay-layer v-model="is_visibleAuthority" :area="['1000px', '700px']" :title="'权限分配'" :btn="visible_opteronAuthority"  :shadeClose="false">
        <div style="padding: 20px 40px 20px 20px;">
          <lay-tree :data="authorityTree" :showCheckbox="true" v-model:checkedKeys="checkedKeys2" :showLine="false" default-expand-all :replace-fields="{id: 'key', title: 'title', children: 'children'}">
          </lay-tree>
        </div>
      </lay-layer>
    </div>
  </div>
</template>  
  
  <script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import http from "@/http";
import { layer } from "@layui/layui-vue";
import { time_YY_DD_MM_HH_MI_SS } from "@/tools/time";
import Pagination from "@/components/pagination.vue";
import { useCounterStore } from "@/current";
import { storeToRefs } from "pinia"; // cnpm i pinia --save  2.1.3
const store = useCounterStore();
const { system, nowMenuBtnArr } = storeToRefs(store); //  数据

interface formType {
  rolename: string;
  rolecode: string;
  state: boolean;
  userList: [];
  describes: string;
}
// 控制弹层
const is_visible = ref<boolean>(false);
// 弹层标题
const visibleTitle = ref<string>("");
// 表格数据
const dataSource = ref([]);
//当前页码数
const pageNo = ref<number | string>(1);
// 每页的条数
const pageSize = ref<number | string>(10);
// 分页
const limit = ref(10);
const total = ref(0);
const currentPage = ref(1);

// 判断要修改时是否不可修改状态
let cannotEdit = ref(true)

// 角色代码
const rolecode = ref(undefined);
const rolename = ref(undefined);

// 添加？ 删除？  查看
const isAddEdit = ref("");
// 表单数据
const form = reactive<formType>({
  rolename: "",
  rolecode: "",
  state: true,
  userList: [],
  describes: "",
});

// 表格
const columns = ref([
  { title: "角色名", key: "rolename" },
  // { title: "角色代码", key: "rolecode" },
  { title: "创建时间", key: "createday" },
  { title: "创建人", key: "creator" },
  { title: "状态", key: "state", customSlot: "state" },
  { title: "操作", key: "operator", customSlot: "operator" },
]);

const get_list = async (page, limit) => {
  const res = await http.corsApi("/secRole/page", "get", {
    pageNo: page,
    pageSize: limit,
    rolecode: rolecode.value,
    rolename: rolename.value,
  });
  console.log(res);

  // res.data.list.map((item) => {
  //   item["state"] = item.state == 1 ? true : false;
  // });

  total.value = res.data.totalCount;
  currentPage.value = res.data.pageNo;
  dataSource.value = res.data.list;
};

// 新增
const add = async () => {
  cannotEdit.value = true
  visibleTitle.value = "新增";
  is_visible.value = true;
  isAddEdit.value = "add";
  get_user_list();

  form.rolename= ""
  form.rolecode= ""
  form.state= true
  form.userList= []
  form.describes= ""


};

// 修改
const edit_tab = async (row) => {
  cannotEdit.value = true
  const result:any = await http.get(`/secRole/judge/${row.rolecode}`, {});
  console.log(result)
  if(result.code != 200) {
    cannotEdit.value = false
  } else if(!result.data) {
    cannotEdit.value = false
  }

  console.log(row);
  await get_role_detail(row.rolecode);
  isAddEdit.value = "edit";
  visibleTitle.value = "修改";
  form.rolename = row.rolename;
  form.rolecode = row.rolecode;
  form.state = row.state == 0 ? true : false;
  is_visible.value = true;
};

const view_tab = async (row) => {
  console.log(row);
  await get_role_detail(row.rolecode);
  isAddEdit.value = "view";
  visibleTitle.value = "查看";
  form.rolename = row.rolename;
  form.rolecode = row.rolecode;
  form.state = row.state == 0 ? true : false;
  is_visible.value = true;
};

// 删除
const del_tab = async (row:any) => {
  console.log(row);

  const result:any = await http.get(`/secRole/judge/${row.rolecode}`, {});
  console.log(result)
  if(result.code != 200) {
    layer.confirm(`${result.msg}`, { icon: 2 });
    return 
  } else if(!result.data) {
    layer.confirm(`该角色下有人，不可删除`, { icon: 2 });
    return 
  }

  layer.confirm("确认要删除吗？", {
    btn: [
      {
        text: "确认",
        callback: async (id) => {
          const res = await http.corsApi("/secRole/batch", "delete", [row.rolecode]);
          console.log(res);
          if (res.data) {
            await get_list(pageNo.value, pageSize.value);
            await layer.confirm("删除成功", { icon: 1 });
          }
          layer.close(id);
        },
      },
      {
        text: "取消",
        callback: (id) => {
          layer.close(id);
        },
      },
    ],
  });
}; 

// 修改状态 
const switch_change = async (row:any, e:Event) => {
  console.log(row, e);
  
  const result:any = await http.get(`/secRole/judge/${row.rolecode}`, {});
  console.log(result)
  if(result.code != 200) {
    layer.confirm(`${result.msg}`, { icon: 2 });
    get_list(pageNo.value, pageSize.value);
    return 
  } else if(!result.data) {
    layer.confirm(`该角色下有人，不可删除`, { icon: 2 });
    get_list(pageNo.value, pageSize.value);
    return 
  }
  

  const res = await http.corsApi(`/secRole/${e}/updateStatus/${row.rolecode}`, "put", {});
  console.log(res); 
  if (res.data) {
    layer.msg("状态修改成功", { time: 1500, icon: 1 });

    await get_list(pageNo.value, pageSize.value);
  }
  
  // /secRole/{state}/updateStatus/{rolecode}
};

// 查询
const search_table = async () => {
  await get_list(pageNo.value, pageSize.value);
};

// 重置
const resert = async () => {
  rolecode.value = undefined;
  rolename.value = undefined;
  await get_list(pageNo.value, pageSize.value);
};

const layFormRef11 = ref();
// 弹层操作
const visible_opteron = ref([
  {
    text: "确认",
    callback: async () => {
      //   layer.confirm("确认操作", { shade: false,icon:1 });
      console.log(form);

      if (isAddEdit.value == "view") {
        is_visible.value = false;
        return false;
      }

      layFormRef11.value.validate(async (isValidate, model, errors) => {
        if (isValidate) {
          let method = "";
          if (isAddEdit.value == "add") {
            method = "post";
          } else if (isAddEdit.value == "edit") {
            method = "put";
          }

          const res = await http.corsApi("/secRole", method, {
            createday: time_YY_DD_MM_HH_MI_SS(new Date().getTime()), //创建时间
            creator: system.value.id,
            // rolecode: isAddEdit.value == "add" ? new Date().getTime() : form.rolecode,
            rolecode: form.rolecode,
            rolename: form.rolename,
            state: form.state ? 0 : 1,
            userList: form.userList,
            describes: form.describes,
          });
          console.log(res);
          if (res.data) {
            layer.confirm(method == "post" ? "添加成功" : "修改成功", { icon: 1 });
            await get_list(pageNo.value, pageSize.value);
            is_visible.value = false;
          }
        }
      });
    },
  },
  {
    text: "取消",
    callback: () => {
      is_visible.value = false;
      //   layer.confirm("取消操作", { shade: false,icon:2 });
    },
  },
]);

// 权限配置
// 选中
const checkedKeys2 = ref([]);
// 权限树形数据
const authorityTree = ref([]);
// 控制权限
const is_visibleAuthority = ref(false);

// 权限弹层操作
const visible_opteronAuthority = ref([
  {
    text: "确认",
    callback: async () => {
      console.log(checkedKeys2.value);
      console.log(rowTable.value);
      const res = await http.corsApi("/secRole/allocation", "post", {
        permissionId: "",
        permissionIdList: checkedKeys2.value,
        rolecode: rowTable.value.rolecode,
      });
      console.log(res);

      if (res.data) {
        layer.confirm("分配成功", { shade: true, icon: 1 });
        await get_list(pageNo.value, pageSize.value);
        is_visibleAuthority.value = false;
      }

      //   layer.confirm("确认操作", { shade: false,icon:1 });
    },
  },
  {
    text: "取消",
    callback: () => {
      is_visibleAuthority.value = false;
      //   layer.confirm("取消操作", { shade: false,icon:2 });
    },
  },
]);

// 当前行数据
const rowTable = ref();
// 打开权限分配
const authority_open = (row) => {
  console.log(row);
  rowTable.value = row;
  get_tree_data();
  is_visibleAuthority.value = true;

  get_role_auth(row.rolecode);
};

// 分页事件
const page_change = async (page, limt) => {
  console.log(page, limt);
  currentPage.value = page;
  await get_list(page, limt);
};

const get_tree_data = async () => {
  const res = await http.corsApi("/secRole/tree", "get", {});
  console.log(res);
  authorityTree.value = res.data;
};

// 获取当前角色的权限列表
const get_role_auth = async (id) => {
  const res = await http.corsApi(`/secRole/getPermissionId/${id}`, "get", {});
  console.log(res);
  checkedKeys2.value = res.data;
};

const userList = ref([]);
// 用户列表
const get_user_list = async () => {
  const res = await http.corsApi("/secUser/getUserList", "get", {});
  console.log(res);
  userList.value = res.data;
};
// 角色详情
const get_role_detail = async (id) => {
  const res = await http.corsApi(`/secRole/${id}`, "get", {});
  console.log(res);
  await get_user_list();
  form.userList = res.data.userList;
};
// 页面初始化
onMounted(() => {
  get_list(pageNo.value, pageSize.value);
});
</script>
  
  <style scoped lang="scss">
.user {
  width: 100%;
  height: 100%;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  &_title {
    display: flex;
    justify-content: space-between;
    > div {
      display: flex;
      align-items: center;
      margin-right: 35px;
      span {
        // width: 70px;
        white-space: nowrap;
        text-align: right;
      }
      .layui-input {
        width: 300px;
      }
    }
  }

  &_btn {
    // margin-right: 8px;
    margin-top: 20px;
  }
  &_table {
    margin-top: 20px;
  }
}
</style>